<template>
  <view class="nurse-add-container">
    <view class="page-header">
      <text class="page-title">新增护士</text>
      <text class="page-subtitle">添加新的护士信息</text>
    </view>

    <view class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">关联用户</text>
          <picker 
            :range="userOptions" 
            range-key="display_name" 
            :value="selectedUserIndex"
            @change="onUserChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedUserDisplay || '请选择关联的护士用户' }}</text>
            </view>
          </picker>
          <text class="form-hint">选择角色为"护士"的用户账号</text>
          <text v-if="errors.user_id" class="error-text">{{ errors.user_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">职称等级</text>
          <radio-group @change="onTitleLevelChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.title_level === 0" color="#007aff"/>
              <text class="radio-text">护士</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.title_level === 1" color="#007aff"/>
              <text class="radio-text">护师</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.title_level === 2" color="#007aff"/>
              <text class="radio-text">主管护师</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.title_level === 3" color="#007aff"/>
              <text class="radio-text">副主任护师</text>
            </label>
            <label class="radio-item">
              <radio value="4" :checked="formData.title_level === 4" color="#007aff"/>
              <text class="radio-text">主任护师</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">头像</text>
          <uni-file-picker 
            v-model="photoFileList"
            file-mediatype="image"
            mode="grid"
            :limit="1"
            :auto-upload="false"
            @select="handlePhotoSelect"
            @delete="handlePhotoDelete"
          />
          <text class="form-hint">专业形象照，建议尺寸：400x400像素</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">执业信息</text>
        
        <view class="form-item">
          <text class="form-label">执业证号</text>
          <uni-easyinput 
            v-model="formData.license_no"
            placeholder="请输入护士执业证号"
            :clearable="true"
            trim="all"
            @blur="validateLicenseNo"
          />
          <text class="form-hint">15位数字格式</text>
          <text v-if="errors.license_no" class="error-text">{{ errors.license_no }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">所属科室</text>
          <uni-easyinput 
            v-model="formData.department"
            placeholder="如：口腔科、护理部等"
            :clearable="true"
            trim="all"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">专业背景</text>
        
        <view class="form-item">
          <text class="form-label">教育背景</text>
          <uni-easyinput 
            v-model="formData.education_background"
            placeholder="如：某某大学护理学专业"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">工作年限</text>
          <uni-easyinput 
            v-model="formData.years_experience"
            type="number"
            placeholder="请输入工作年限"
            :clearable="true"
          />
        </view>

        <view class="form-item">
          <text class="form-label">个人简介</text>
          <textarea 
            v-model="formData.introduction" 
            class="form-textarea" 
            placeholder="请输入护士个人简介"
            maxlength="1000"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">工作信息</text>
        
        <view class="form-item">
          <text class="form-label required">工作状态</text>
          <radio-group @change="onWorkingStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.working_status === 0" color="#007aff"/>
              <text class="radio-text">在职</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.working_status === 1" color="#007aff"/>
              <text class="radio-text">请假</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.working_status === 2" color="#007aff"/>
              <text class="radio-text">外出</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">提交</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const photoFileList = ref([])
const userOptions = ref([])
const selectedUserIndex = ref(-1)

const formData = reactive({
  user_id: '',
  title_level: 0,
  photo: '',
  license_no: '',
  department: '',
  education_background: '',
  years_experience: '',
  introduction: '',
  working_status: 0
})

const selectedUserDisplay = computed(() => {
  if (selectedUserIndex.value >= 0 && userOptions.value[selectedUserIndex.value]) {
    return userOptions.value[selectedUserIndex.value].display_name
  }
  return ''
})

const errors = reactive({
  user_id: '',
  license_no: ''
})

onMounted(async () => {
  await loadNurseUsers()
})

async function loadNurseUsers() {
  try {
    uni.showLoading({ title: '加载用户列表...' })
    
    // 调用云对象方法获取可用的护士用户列表
    const nursesObj = uniCloud.importObject('dh-nurses')
    const result = await nursesObj.getAvailableNurseUsers()
    
    uni.hideLoading()
    
    if (result.code === 200 && result.data) {
      // 格式化用户数据
      userOptions.value = result.data.map(user => {
        let displayName = ''
        if (user.realname_auth && user.realname_auth.real_name) {
          displayName = user.realname_auth.real_name
        } else if (user.nickname) {
          displayName = user.nickname
        } else if (user.username) {
          displayName = user.username
        } else if (user.mobile) {
          displayName = user.mobile
        } else {
          displayName = user._id
        }
        
        return {
          _id: user._id,
          display_name: displayName,
          username: user.username,
          nickname: user.nickname,
          mobile: user.mobile
        }
      })
      
      if (userOptions.value.length === 0) {
        uni.showToast({
          title: '没有可用的护士用户（所有护士用户都已创建护士信息）',
          icon: 'none',
          duration: 3000
        })
      }
    } else {
      throw new Error(result.message || '加载失败')
    }
  } catch (err) {
    uni.hideLoading()
    console.error('加载用户列表失败:', err)
    uni.showToast({ 
      title: '加载用户列表失败：' + (err.message || '未知错误'), 
      icon: 'none' 
    })
  }
}

function onUserChange(e) {
  selectedUserIndex.value = parseInt(e.detail.value)
  if (selectedUserIndex.value >= 0 && userOptions.value[selectedUserIndex.value]) {
    formData.user_id = userOptions.value[selectedUserIndex.value]._id
    errors.user_id = ''
  } else {
    formData.user_id = ''
  }
}

function onTitleLevelChange(e) {
  formData.title_level = parseInt(e.detail.value)
}

function onWorkingStatusChange(e) {
  formData.working_status = parseInt(e.detail.value)
}

function validateLicenseNo() {
  if (!formData.license_no || formData.license_no.trim().length === 0) {
    errors.license_no = ''
    return
  }
  
  // 验证护士执业证号格式：15位数字
  // 格式：前6位行政区划代码 + 4位年份 + 4位顺序号 + 1位校验码
  const licenseNoPattern = /^\d{15}$/
  if (!licenseNoPattern.test(formData.license_no)) {
    errors.license_no = '护士执业证号格式不正确（应为15位数字）'
  } else {
    errors.license_no = ''
  }
}

function handlePhotoSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    photoFileList.value = e.tempFiles
  }
}

function handlePhotoDelete(e) {
  photoFileList.value = []
}

async function uploadPhotoToCloud() {
  if (!photoFileList.value || photoFileList.value.length === 0) {
    return null
  }
  
  try {
    const tempFile = photoFileList.value[0]
    const uploadResult = await uniCloud.uploadFile({
      filePath: tempFile.path,
      cloudPath: `nurses/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${tempFile.name.split('.').pop()}`
    })
    // 返回符合数据库schema的file对象结构
    return {
      name: uploadResult.fileID.split('/').pop(),
      extname: tempFile.name.split('.').pop(),
      url: uploadResult.fileID,
      size: tempFile.size || 0,
      file_id: uploadResult.fileID
    }
  } catch (err) {
    throw err
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.user_id || formData.user_id.trim().length === 0) {
    errors.user_id = '请选择关联用户'
    isValid = false
  } else {
    errors.user_id = ''
  }
  
  // 如果填写了执业证号，验证格式
  if (formData.license_no && formData.license_no.trim().length > 0) {
    const licenseNoPattern = /^\d{15}$/
    if (!licenseNoPattern.test(formData.license_no)) {
      errors.license_no = '护士执业证号格式不正确（应为15位数字）'
      isValid = false
    } else {
      errors.license_no = ''
    }
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '提交中...' })
    
    let photoUrl = ''
    if (photoFileList.value && photoFileList.value.length > 0) {
      try {
        uni.showLoading({ title: '上传照片中...' })
        photoUrl = await uploadPhotoToCloud()
      } catch (uploadErr) {
        uni.hideLoading()
        uni.showToast({ title: '照片上传失败', icon: 'none' })
        return
      }
    }
    
    // 构建提交数据
    const submitData = {
      user_id: formData.user_id,
      title_level: formData.title_level,
      license_no: formData.license_no,
      department: formData.department,
      education_background: formData.education_background,
      years_experience: parseInt(formData.years_experience) || 0,
      introduction: formData.introduction,
      working_status: formData.working_status
    }
    
    // 只有有照片URL时才添加photo字段
    if (photoUrl) {
      submitData.photo = photoUrl
    }
    
    // 调用云对象方法创建护士
    const nursesObj = uniCloud.importObject('dh-nurses')
    const result = await nursesObj.createNurse(submitData)
    
    uni.hideLoading()
    
    if (result.code === 201 && result.data && result.data._id) {
      uni.showToast({ title: result.message || '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/nurses/list' })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '创建失败', icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ title: err.message || '创建失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/nurses/list' })
}
</script>

<style lang="scss" scoped>
.nurse-add-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
